package cn.house.rent.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class RentFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        //统一设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //判定是否登录  用户登录放行   否则重定向到登录页
        HttpSession session = req.getSession();
        //获取session存储的用户是否在线
        Object user = session.getAttribute("user");
        String url = req.getRequestURI();
        //放行静态资源
        if (url.endsWith(".js")||url.endsWith(".css")||url.endsWith(".ico")||url.endsWith(".jpg")||url.endsWith(".png")||url.endsWith(".ttf")||url.endsWith(".woff2")||url.endsWith(".woff")) {
            filterChain.doFilter(req,resp);
        }else if(url.endsWith(".eot")||url.endsWith(".svg")||url.endsWith(".otf")|| url.endsWith(".gif")){
            filterChain.doFilter(req,resp);
        }else if(url.endsWith("houseinfo.jsp")||url.endsWith("houselist.jsp")||url.endsWith("login.jsp")||url.endsWith("main.jsp")||url.endsWith("register.jsp")){
            filterChain.doFilter(req,resp);
        }else if(url.endsWith("forget.jsp")||url.endsWith("loginback.jsp")){
            filterChain.doFilter(req,resp);
        }else if(url.endsWith("login")||url.endsWith("register")||url.endsWith("registerCheck")||url.endsWith("emailCheck")){//放行登录和注册操作
            filterChain.doFilter(req,resp);
        }else if(url.endsWith("getHouseByInfo")||url.endsWith("getHouseAllById")||url.endsWith("getHouseAllById")||url.endsWith("email")||url.endsWith("forget")||url.endsWith("getCaptcha")){
            filterChain.doFilter(req,resp);
        }else{
            if(user != null){
                filterChain.doFilter(req,resp);
            }else{//没有登录  重定向到登录页
                resp.sendRedirect(req.getContextPath()+"/jsp/main.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
